<?php

namespace app\controller;

use app\service\BannerService;
use app\service\GoodsService;
use app\service\MemberService;
use app\service\RandomNickNameService;
use app\service\ShortcutService;
use support\facade\Logger;
use support\Request;
use const support\ERROR;

class IndexController
{
    public function index(): \support\Response
    {
        //获取轮播图信息
        $banners=BannerService::lists();
        //获取快捷键信息
        $shortcuts=ShortcutService::lists();
        //获取推荐商品信息
        $goods=GoodsService::getPushLists();
        //获取报名实况信息
        $randInfos=RandomNickNameService::getRandomInfos(50);
        $data=[
           'banner'     =>$banners,
           'shortcuts'  =>$shortcuts,
           'goods'      =>$goods,
           'actuality'  =>$randInfos
        ];
        return buildSuccess($data);
    }

    //获取客服配置
    public function kfConfig(): \support\Response
    {
        //获取客服
        $config['wechat_account']=13651267835;
        $config['contact_mobile']=13651267835;
        return buildSuccess($config);
    }

    //微信公众号授权回跳页面
    public function memberWechatOauth(Request $request,$thirdOauthId): \support\Response
    {
        if ($thirdOauthId=='oauthEnd'){
            return view('index/oauth',[
                'status'=>1
            ]);
        }
        //前端传值
        $code=$request->get('code','');
        if (!$code){
            return view('index/oauth',[
                'status'=>2
            ]);
        }
        try {
            //获取微信配置
            $config=config('wechat.wechat_official');
            //获取基本信息
            $serverLoginUrl = "https://api.weixin.qq.com/sns/oauth2/access_token?appid=".$config['app_id']."&secret=".$config['secret']."&code={$code}&grant_type=authorization_code";
            $result = @file_get_contents($serverLoginUrl);
            $result = json_decode($result, true);
            Logger::app('微信公众号授权回跳页面：基本信息','info',$result);
            if (!empty($result['errcode'])){
                return view('index/oauth',[
                    'status'=>3
                ]);
            }
            //获取解密token
            $serverLoginUrl = "https://api.weixin.qq.com/sns/userinfo?access_token=".$result['access_token']."&openid=".$result['openid']."&&lang=zh_CN";
            $result = @file_get_contents($serverLoginUrl);
            $userInfo = json_decode($result, true);
            Logger::app('微信公众号授权回跳页面：基本信息','info',$userInfo);
            MemberService::modifyNicknameAndAvatar($thirdOauthId,$userInfo['nickname'],$userInfo['headimgurl']);
            $redirectUrl=sprintf("%s/h5/memberWechatOauth/oauthEnd",env('APP_URL'));
            return redirect($redirectUrl);
        }catch (\Throwable $e){
            return buildFail(ERROR,$e->getMessage());
        }
    }

}
